package fctuc.dei.myTwitter.database;

import java.sql.*;

import fctuc.dei.myTwitter.constants.MyTwitterConstants;

public class DbWrapper {

	Statement stmt;
	Connection con;
	
	private DbWrapper(){
	}
	
	private static class SingletonHolder{
		private static final DbWrapper INSTANCE = new DbWrapper();
	}
	
	public static DbWrapper getInstance(){
		return SingletonHolder.INSTANCE;
	}
	
	public void connect(){
		
		try {
			//Register de JDBC driver for MySQL
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			
			//Connect
			con = DriverManager.getConnection(
												MyTwitterConstants.DB_URL,
												MyTwitterConstants.DB_USERNAME,
												MyTwitterConstants.DB_PASSWORD
												);
			

			//Get a Statement object
			stmt = con.createStatement();
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public ResultSet executeSelect(String select){
		
		try{
			if(!this.con.isClosed()){
				this.stmt.executeQuery(select);
				return stmt.getResultSet();
			}
		}
		catch (SQLException ex){
			while (ex != null){
				System.out.println("SQL Exception: " + ex.getMessage());
				ex = ex.getNextException();
			}
		}
		return null;
	}
	
	public void executeNonSelect (String sql){
		try{
			if(!this.con.isClosed()){
				this.stmt.executeUpdate(sql);
//				this.con.commit();
			}
		}
		catch (SQLException ex){
			while (ex != null){
				System.out.println("SQL Exception: " + ex.getMessage());
				ex = ex.getNextException();
			}
		}
	}
	
	public void closeConnection(){
		try{
			this.stmt.close();
			this.con.close();
		}
		catch (SQLException ex){
			while (ex!= null){
				System.out.println("SQL Exception: " + ex.getMessage());
				ex = ex.getNextException();
			}
		}
	}
	
}

